import 'package:flutter/material.dart';
import '../models/git_repo.dart';
import '../services/api_service.dart';
import '../utils/date_util.dart';
import '../screens/repo_detail_screen.dart';

class GitRepoScreen extends StatefulWidget {
  const GitRepoScreen({
    Key? key,
  }) : super(key: key);

  @override
  State<GitRepoScreen> createState() => _GitRepoScreenState();
}

class _GitRepoScreenState extends State<GitRepoScreen> {
  final ApiService _apiService = ApiService();
  final List<GitRepo> _repos = [];
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _loadRepos();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _loadRepos({bool refresh = false}) async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
      if (refresh) {
        _currentPage = 1;
        _repos.clear();
      }
    });

    try {
      final newRepos = await _apiService.getUserRepos(
        page: _currentPage,
      );
      setState(() {
        if (refresh) {
          _repos.clear();
        }
        _repos.addAll(newRepos);
        _hasMore = newRepos.isNotEmpty;
        _currentPage++;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载失败: $e')),
      );
    }
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      if (!_isLoading && _hasMore) {
        _loadRepos();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的仓库'),
      ),
      body: RefreshIndicator(
        onRefresh: () => _loadRepos(refresh: true),
        child: ListView.builder(
          controller: _scrollController,
          padding: const EdgeInsets.all(16),
          itemCount: _repos.length + (_hasMore ? 1 : 0),
          itemBuilder: (context, index) {
            if (index == _repos.length) {
              return const Center(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: CircularProgressIndicator(),
                ),
              );
            }

            final repo = _repos[index];
            return Card(
              margin: const EdgeInsets.only(bottom: 16),
              elevation: 2,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              child: InkWell(
                borderRadius: BorderRadius.circular(12),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => RepoDetailScreen(
                        owner: repo.owner.login,
                        repo: repo.path,
                        sha: repo.default_branch,
                        isRoot: true,
                      ),
                    ),
                  );
                },
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              repo.name,
                              style: const TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          if (repo.private)
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 8,
                                vertical: 4,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.grey[200],
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: const Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(Icons.lock, size: 14),
                                  SizedBox(width: 4),
                                  Text(
                                    '私有',
                                    style: TextStyle(fontSize: 12),
                                  ),
                                ],
                              ),
                            ),
                        ],
                      ),
                      if (repo.description?.isNotEmpty == true) ...[
                        const SizedBox(height: 8),
                        Text(
                          repo.description!,
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 14,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                      const SizedBox(height: 12),
                      Row(
                        children: [
                          if (repo.language?.isNotEmpty == true) ...[
                            _buildInfoChip(
                              icon: Icons.code,
                              label: repo.language!,
                            ),
                            const SizedBox(width: 12),
                          ],
                          _buildInfoChip(
                            icon: Icons.star,
                            label: repo.stargazers_count.toString(),
                          ),
                          const SizedBox(width: 12),
                          _buildInfoChip(
                            icon: Icons.fork_right,
                            label: repo.forks_count.toString(),
                          ),
                          const Spacer(),
                          Text(
                            DateUtil.formatTimeAgo(repo.updated_at),
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 12,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildInfoChip({
    required IconData icon,
    required String label,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: Colors.grey[700]),
          const SizedBox(width: 4),
          Text(
            label,
            style: TextStyle(
              color: Colors.grey[700],
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }
}
